package com.zcup.miaosha.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zcup.miaosha.entity.User;
import com.zcup.miaosha.mapper.UserMapper;
import com.zcup.miaosha.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public int saveUserCount(Integer userId) {
        //根据用户id生成计数key
        String limitKey = "LIMIT_" + userId;

        //获取redis中指定key的调用次数
        String limitNum = redisTemplate.opsForValue().get(limitKey);

        if (limitNum == null) {
            //第一次调用,将值设置为0并放入redis中
            redisTemplate.opsForValue().set(limitKey,"1",3600, TimeUnit.SECONDS);
            return 1;
        }else {
            //非第一次调用
            redisTemplate.opsForValue().increment(limitKey);
            return Integer.parseInt(limitNum) + 1;
        }
    }

    @Override
    public boolean getUserCount(Integer userId) {
        String limitKey = "LIMIT_" + userId;
        String s = redisTemplate.opsForValue().get(limitKey);
        if (s == null){
            System.out.println("用户:" + userId + "没有登录次数的记录,系统异常");
            return false;
        }
        return Integer.parseInt(s) > 10;
    }
}
